package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/category")
public class CategoryController {

    private final CategoryService categoryService;



    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;

    }

    /**
     * 根据分类的id查询对应的分类对象
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id) {

//        //查询到是category
//        Category category = this.categoryService.getById(id);
//
//        CategoryDTO categoryDTO = new CategoryDTO();
//
//        BeanUtils.copyProperties(category,categoryDTO);
//
//
//        //返回的是categoryDTO
//        return ResponseEntity.ok(categoryDTO);

        return ResponseEntity.ok(new CategoryDTO(categoryService.getById(id)));
    }

    /**
     * 根据分类的id集合查询分类的集合
     * @param ids
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){
//
//        List<Category> categories = this.categoryService.listByIds(ids);
//
//        List<CategoryDTO> categoryDTOS = new ArrayList<>();
//
//        for (Category category : categories) {
//            CategoryDTO categoryDTO = new CategoryDTO();
//            BeanUtils.copyProperties(category,categoryDTO);
//
//            categoryDTOS.add(categoryDTO);
//
//        }


        return ResponseEntity.ok(CategoryDTO.convertEntityList(categoryService.listByIds(ids)));
    }

    /**
     * 根据品牌的id查询对应的分类的集合
     * @param brandId
     * @return
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrand(@RequestParam("id")Long brandId){

        return ResponseEntity.ok(this.categoryService.queryCategoryByBrandId(brandId));
    }

    /**
     * 根据父id查询对应的子分类
     * @param pid
     * @return
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParentId(@RequestParam("pid")Long pid){

        /**
         * 根据父的id查询对应的子==》select * from tb_category where parent_id = 10
         *
         * List<Category>====>List<CategoryDTO>
         */
        return ResponseEntity.ok(
                CategoryDTO.convertEntityList(
                        this.categoryService.query()
                                .eq("parent_id",pid).list()));
    }

}
